﻿using IdentityService.Domain.Aggregates.UserAccountAggregate;
using IdentityService.Domian.Repositories;
using Microsoft.EntityFrameworkCore;

namespace IdentityService.Infrastructure.EFRepositories
{
    public class EFUserAccountRepository : IUserAccountRepository
    {
        private readonly AppIdentityDbContext _context;
        public EFUserAccountRepository(AppIdentityDbContext context) => _context = context;

        public async Task AddAsync(UserAccount user)
        {
            await _context.UserAccount.AddAsync(user);
        }

        public void Delete(UserAccount user)
        {
            _context.UserInfo.Remove(user.UserInfo);
            _context.UserAccount.Remove(user);
        }

        public async Task<bool> CheckUserNameExistedAsync(string userName)
        {
            return await _context.UserAccount.AnyAsync(it => it.UserName == userName);
        }

        public async Task<UserAccount?> FindByIdAsync(long id)
        {
            return await _context.UserAccount.FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<UserAccount?> FindByIdIncludeAllAsync(long id)
        {
            return await _context.UserAccount.Include(it => it.UserInfo).Include(it => it.Roles)
                .Include(it => it.Claims).FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<List<UserAccount>> FindByIdBlukAsync(IList<long> ids)
        {
            return await _context.UserAccount.Where(it => ids.Contains(it.Id)).ToListAsync();
        }

        public async Task<UserAccount?> FindByUserNameAsync(string userName)
        {
            return await _context.UserAccount.FirstOrDefaultAsync(it => it.UserName == userName);
        }

    }
}
